package com.hm.oltu.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hm.common.util.EncryptUtil.Md5;
import com.hm.common.util.StringUtil;
import com.hm.oltu.auto.OltuProperties;
import com.hm.oltu.def.CommonDef;
import com.hm.oltu.def.OauthDef;

@Controller
public class EntranceController {
	
	@Autowired
	private OltuProperties oltuProperties;

	@RequestMapping(value = { "", "/", "/index" })
	public String index(Model model, HttpServletRequest request) {
		return "index";
	}
	
	@RequestMapping(value ="/loginout")
	public String loginOut(Model model, HttpServletRequest request) {
		return "index";
	}
	
	@RequestMapping(value = "/sessionError/index")
	public String sessionError(Model model, HttpServletRequest request) {
		model.addAttribute("error", "会话超时,请重新登陆");
		return "index";
	}
	
	@RequestMapping(value = "/error/index")
	public String error(Model model, HttpServletRequest request) {
		model.addAttribute("error", "用户名/密码错误");
		return "index";
	}
	
	@RequestMapping("/help")
	public String help(){
		return "help";
	}
	
	@RequestMapping(value = "main")
	public String main(Model model) {
		model.addAttribute("message", "567");
		return "main";
	}
	
	@RequestMapping("/404")
	public String error_404() {
		return "error/404";
	}
	
	@RequestMapping("login")
	public String login(HttpServletRequest request, Model model) {
		String username = request.getParameter(OauthDef.LOGIN_USERNAME) + "";
		String password = Md5.getMD5Code(request.getParameter(OauthDef.LOGIN_PASSWORD) + "");
		if (oltuProperties.getRootUser().getPassword().equals(password)
				&& oltuProperties.getRootUser().getUsername().equals(Md5.getMD5Code(username))) {
			request.getSession().setAttribute(CommonDef.BaseInit.SessionOrCookieToken.SESSION_LOGIN_USER_INFO,
					username);
			model.addAttribute("username", username);
			return "redirect:/main?code=" + StringUtil.getCodeNumber();
		}
		return "redirect:/error/index?error=true&code=" + StringUtil.getCodeNumber();
	}
}
